package org.wishwork.api.inventory.count;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wishwork.api.Api;
import org.wishwork.context.Context;
import org.wishwork.helper.HttpHelper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 库存盘点查询
 * @author: WangYX
 * @create: 2022-04-06 17:44
 * @Version: 1.0.0
 **/

public class InventoryCountApi extends Api<List<InventoryCountResponse>, InventoryCountRequest> {

    private static final Logger log = LoggerFactory.getLogger(InventoryCountApi.class);

    private Context context;

    public InventoryCountApi(Context context) {
        this.context = context;
    }

    @Override
    protected String query(InventoryCountRequest inventoryCountRequest) throws Exception {
        String url = "/open/inventory/count/query";
        Map<String, Object> params = new HashMap<>();
        if (!StrUtil.isEmpty(inventoryCountRequest.getIoIds())) {
            params.put("io_ids", inventoryCountRequest.getIoIds());
        }
        if (!StrUtil.isEmpty(inventoryCountRequest.getStatus())) {
            params.put("status", inventoryCountRequest.getStatus());
        }
        return HttpHelper.sendRequest(inventoryCountRequest, params, url);
    }

    @Override
    protected List<InventoryCountResponse> process(JSONObject data, InventoryCountRequest inventoryCountRequest) throws Exception {
        JSONArray datas = data.getJSONArray("datas");
        List<InventoryCountResponse> inventoryCountResponses = datas.toJavaList(InventoryCountResponse.class);
        //判断是否还有下一个
        Boolean has_next = data.getBoolean("has_next");
        if (has_next) {
            Integer index = inventoryCountRequest.getPageIndex();
            InventoryCountRequest build = inventoryCountRequest.toBuilder().pageIndex(++index).build();
            List<InventoryCountResponse> result = business(build);
            inventoryCountResponses.addAll(result);
        }
        return inventoryCountResponses;
    }
}
